package org.springblade.modules.device.task;


import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.modules.alisls.AliSlsProperties;
import org.springblade.modules.alisls.AliyunSlsService;
import org.springblade.modules.device.entity.DeviceAlert;
import org.springblade.modules.device.entity.DeviceDetail;
import org.springblade.modules.device.mapper.DeviceDetailMapper;
import org.springblade.modules.device.service.IDeviceAlertService;
import org.springblade.modules.device.vo.DeviceDetailVo;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
@ConditionalOnProperty(name ="task.enable", havingValue = "true",matchIfMissing = true)
public class DeviceTask {
	@Resource
	private AliyunSlsService aliyunSlsService;
	@Resource
	private AliSlsProperties aliSlsProperties;
	@Resource
	private IDeviceAlertService deviceAlertService;
	@Resource
	private DeviceDetailMapper deviceDetailMapper;

	@Async("coffeeTaskExecutor")
	@Scheduled(cron = "0 0/5 * * * *")
	public void deviceRunStatus() {
		log.info("设备运行变更告警开始");
		deviceAlertService.getDeviceAlert(DeviceAlert.RUN_STATUS_TYPE);
	}


	@Async("coffeeTaskExecutor")
	@Scheduled(cron = "0 0/20 * * * *")
	public void deviceScarceStatus() {
		log.info("设备物料变更告警开始");
		deviceAlertService.getDeviceAlert(DeviceAlert.SCARCE_STATUS_TYPE);
	}


	@Async("coffeeTaskExecutor")
	@Scheduled(cron = "0 0/30 * * * *")
	public void updateDeviceDetails() {
		log.info("设备物料变更告警开始");
		List<DeviceDetailVo> deviceDetailVos = deviceAlertService.allDevices();
		for (DeviceDetailVo deviceDetailVo : deviceDetailVos) {
			DeviceDetail copy = BeanUtil.copy(deviceDetailVo, DeviceDetail.class);
			copy.setUpdateTime(new Date());
			int i = deviceDetailMapper.updateById(copy);
			if(i==0){
				deviceDetailMapper.insert(copy);
			}
		}
	}
}
